# -*- coding: utf-8 -*-
# @Author : Ryhn
import base64
import numpy as np
import pandas as pd
import plotly as py
import plotly.express as px
import shortuuid
from jinja2 import Environment, PackageLoader

from service.path import path
from service import sparkAPI
from service.Email import send_robot_email
from service.main import jira_export


# Todo:pandas数据分析类
class pandas_explan:
     def __init__(self, data):
          self.data = data
          self.DataFrame = None

     def NewDataFrame(self, columns, index):
          self.DataFrame = pd.DataFrame(self.data, columns=columns, index=index)

     def to_html(self):
          return self.DataFrame.to_html(justify="center")

     def countData_value(self, value):
          return self.DataFrame[value].value_counts()

     def sora_lits(self, key:list, value):
          return [value[i] for i in key]

     def countData_keys(self,value):
          return self.DataFrame[value].unique()

     def deleteFrame(self, value):
          self.DataFrame.drop(value, axis=1)

class pandas_Toplotly:
     def make_pie(self, name, value, title, html: bool):
          '''
          输出对应饼图
          :param name:
          :param value:
          :param title:
          :param html:
          :return:
          '''
          proiety_Frame = pd.DataFrame({"key": name, "value": value})
          proiety_pie = px.pie(proiety_Frame, names="key", values="value", title=title)
          proiety_pie.update_layout(
               width=600,  # 设置宽度
               height=400,  # 设置高度
               margin=dict(
                    l=30,  # 左边距
                    r=30,  # 右边距
                    b=30,  # 下边距
                    t=20,  # 上边距
                    pad=2  # 图形内容与其他元素之间的内边距
               ),
               font_family="MSYHL")
          if html:
               chart = py.offline.plot(proiety_pie, include_plotlyjs=False, output_type='div')
               return chart
          else:
               uuid = shortuuid.ShortUUID().random(length=12)
               proiety_pie.write_image(f'{path}/image/'+uuid+'.png')
               return uuid

     def make_bar(self, name, value, title, html: bool):
          '''
          输出柱状图
          :return:
          '''
          type_Frame = pd.DataFrame({"key": name, "value": value})
          type_pie = px.bar(type_Frame, title=title, x="key", y="value")
          type_pie.update_layout(
               width=400,  # 设置宽度
               height=300,  # 设置高度
               margin=dict(
                    l=25,  # 左边距
                    r=25,  # 右边距
                    b=25,  # 下边距
                    t=30,  # 上边距
                    pad=2  # 图形内容与其他元素之间的内边距
               ),
               font_family="MSYHL"
          )
          if html:
               chart = py.offline.plot(type_pie, include_plotlyjs=False, output_type='div')
               return chart
          else:
               uuid = shortuuid.ShortUUID().random(length=12)
               type_pie.write_image(f'{path}/image/'+uuid + '.png')
               return uuid


def render(Issue, project, tester, chart1, chart2,chart3, table, result, text, AI):
     env = Environment(
          loader=PackageLoader("templates", "template"))
     template = env.get_template("reporter.j2")
     context = template.render(title=Issue.title, summary=Issue.description, project=project,
                     url=Issue.url, tester=tester, tester1=Issue.marker,
                     chart1=chart1, chart2=chart2, chart3=chart3, table=table, result=result, text=text, AI=AI)
     return context

def image_base64(path):
     '''
     读取图片将其内容转成html
     :param path:
     :return:
     '''
     with open(path, 'rb') as f:
          a = f.read()
     return base64.b64encode(a).decode("utf-8")


def main(jira_key, jira_user, jira_password, jira_url, result, text, api, api_secret, api_key, email_user, email_pass, receiver):
     # 登录jira,进行数据获取
     option = jira_export(jira_user, jira_password, jira_url)
     BugList, Issue = option.GetData(jira_key)
     # 数据处理
     numy = np.array([i.__list__() for i in BugList])
     nump1 = np.array([i.tester for i in BugList])
     tester = pd.DataFrame({"name": nump1})
     tester_value = tester['name'].unique()
     # bug内容进行表格可视化
     jira_pandas =pandas_explan(numy)
     ryhn_plotly = pandas_Toplotly()
     jira_pandas.NewDataFrame(columns=['名称', '类型', '优先级', '状态', '处理人'], index=[str(i) for i in range(1, numy.shape[0]+1,1)])
     # 背景内容进行表格可视化
     project_pandas = pandas_explan(np.array([[Issue.title, ','.join(jira_pandas.countData_keys("处理人")),
                                               ','.join(tester_value),Issue.startTime,Issue.endTime]]))
     project_pandas.NewDataFrame(columns=['项目名称', '开发人员', '测试人员', '测试开始时间', '测试结束时间'],
                                 index=['1'])
     project_html = project_pandas.to_html()
     # 对应echart图输出为html形式
     proiety = ryhn_plotly.make_pie(jira_pandas.countData_keys("优先级"), jira_pandas.sora_lits(jira_pandas.countData_keys("优先级"),jira_pandas.countData_value("优先级")), "优先级占比", False)
     type = ryhn_plotly.make_bar(jira_pandas.countData_keys("类型"), jira_pandas.sora_lits(jira_pandas.countData_keys("类型"),jira_pandas.countData_value("类型")), "问题类型情况", html=False)
     explaner = ryhn_plotly.make_bar(jira_pandas.countData_keys("处理人"), jira_pandas.sora_lits(jira_pandas.countData_keys("处理人"),jira_pandas.countData_value("处理人")), "处理人情况", html=False)
     # 对应数据表输出为html形式
     bug = jira_pandas.to_html()
     # people = jira_pandas.countData_keys(value="处理人")
     # 对接讯飞ai来对bug进行ai分析
     AI = sparkAPI.ai_import(''.join([i.__str__() for i in BugList]), api, api_secret, api_key)
     context = render(Issue, project=project_html, tester=','.join(tester_value), chart1=image_base64(f'{path}/image/'+ proiety+'.png'),
                      chart2=image_base64(f'{path}/image/' + type+'.png'), chart3=image_base64(f'{path}/image/'+explaner+'.png'), AI=AI.replace('''\n''', '<br>'),
                      table=bug, result=result, text=text)
     # 邮件发送
     send_robot_email(Subject=f'【测试报告】{Issue.title}', message=context,
                      username=email_user, password=email_pass,
                      receiver=receiver)